<script setup>
import { inject, ref } from "vue";
import html2canvas from "html2canvas";
import stepsview from "../components/steps/steps.vue";
import { useCounterStore } from "@/stores/upgrade";
import { handleGoBack } from "@/utils/router";
import {
  upgradecreate,
  upgradeagreeInfo,
  upPageGetAgreeApi,
  newAgencyCreate,
} from "@/services/upfrade";
import { uploadfile } from "@/services/upload";
import { onLoad, onShow } from "@dcloudio/uni-app";
import { base_URL } from "@/utils/http";

import { baseagree } from "@/services/user";

const level_id = ref("");
const id = ref("");
const product_id = ref("");
const type = ref("");
const pay_status = ref("");
const agree = ref("");
const content = ref({});
const contentobj = ref({});
const capture = ref(null);

const isCountDown = ref(false);
const payobj = ref({});

const upgradeshow = ref(false);

onLoad((e) => {
  level_id.value = e.level_id ? e.level_id : "";
  id.value = e.id ? e.id : "";
  product_id.value = e.product_id ? e.product_id : "";
  type.value = e.type ? e.type : "";
  pay_status.value = e.pay_status ? e.pay_status : "";
  payobj.value = e.payobj ? JSON.parse(e.payobj) : "";
  uni.$u.toast(payobj.value);
  console.log("payobj", payobj.value);

  uni.setStorageSync("Authorization", decodeURIComponent(e.Authorization));
  console.log(
    "payobj",
    payobj.value,
    decodeURIComponent(e.Authorization),
    e.Authorization
  );
  agree.value = e.level_id
    ? "distribution_agency_agree "
    : "service_center_agree";

  baseagreefun();
});

onShow(() => {
  signature.value = "";
});
// const form = useCounterStore ();

const dateobj = useCounterStore();

const current = ref(1);
const signature = ref("");
const file = ref(null);
if (dateobj.formdate.signature) {
  signature.value = dateobj.formdate.signature;
}

async function baseagreefun() {
  // let res = await baseagree({
  //   code: agree.value,
  // });

  let ress = await upPageGetAgreeApi({});
  // content.value = ress.data;

  contentobj.value = ress.data.content
    .replace("{$name}", payobj.value.name)
    .replace("{$card_no}", payobj.value.card_no)
    .replace(
      "{$address}",
      payobj.value.operating_area.province +
        payobj.value.operating_area.city +
        payobj.value.operating_area.area +
        payobj.value.operating_area.street
    );
}

async function signatureEvent(base64) {
  // #ifdef H5 || APP-PLUS
  signature.value = base64;
  // #endif

  // #ifdef MP-WEIXIN

  let res = await base64ToTempFilePath(base64);

  signature.value = res;
  // base64ToTempFilePath(
  //   base64,
  //   function (tempFilePath) {
  //     console.log("转换成功，临时地址为:", tempFilePath);
  //     signature.value = tempFilePath; // 会在canvas中调用
  //   },
  //   function () {
  //     console.log("转换失败");
  //   }
  // );

  // #endif

  // var imageUrl = createImageUrlFromBase64(base64);
}

// 将base64图片转换为临时地址
// function base64ToTempFilePath(base64Data, success, fail) {
//   const fs = uni.getFileSystemManager();
//   const fileName = "temp_image_" + Date.now() + ".png"; // 自定义文件名，可根据需要修改
//   const filePath = uni.env.USER_DATA_PATH + "/" + fileName;
//   // const buffer = uni.base64ToArrayBuffer(base64Data);

//   console.log(fileName, filePath);
//   fs.writeFile({
//     data: base64Data,
//     encoding: "base64",
//     success() {
//       success && success(filePath);
//     },
//     fail() {
//       fail && fail();
//   });
// }

async function base64ToTempFilePath(base64Data) {
  const fs = uni.getFileSystemManager();
  const fileName = "LotteryActivity_" + Date.now() + ".png"; // 自定义文件名，可根据需要修改
  console.log("23234324", uni.env);
  const filePath = uni.env.USER_DATA_PATH + "/" + fileName;
  console.log("232343245");
  const base64 = base64Data.split(",")[1]; //移除固定头部
  const buffer = uni.base64ToArrayBuffer(base64);
  let promise = await new Promise((resolve, reject) => {
    fs.writeFile({
      filePath,
      data: buffer,
      encoding: "binary",
      success(res) {
        resolve(filePath); // fulfilled
      },
      fail(err) {
        reject(err); // rejected
      },
    });
  });
  return promise;
}

function clearshart() {
  signature.value = "";
  file.value = "";
}

const time = ref(3);
const onChange = (e) => {
  time.value = e.seconds;
};
const lastfun = () => {
  uni.navigateBack();
};
const istj = ref(false);
const paid = ref("");

const nextfun = async () => {
  if (istj.value) {
    return;
  }
  istj.value = true;
  uni.showLoading({
    title: "协议生成中",
    mask: true,
  });
  if (time.value > 0) {
    return;
  }
  if (!signature.value) {
    uni.$u.toast("请上传签名");
    return;
  }

  console.log(dateobj.formdate, "dateobj.formdate");

  try {
    const element = capture.value;
    console.log(element);
    const canvas = await html2canvas(element, {
      useCORS: true, // 允许跨域图片
      allowTaint: false, // 不允许污染
    });
    const dataURL = canvas.toDataURL("image/png");
    console.log(dataURL); // 这里可以将 dataURL 保存或显示
    uni.uploadFile({
      url: base_URL + "/api/upload/file",
      filePath: dataURL,
      name: "file",
      formData: {
        user: "test",
      },
      header: {
        Authorization: uni.getStorageSync("Authorization"),
      },
      success: async (uploadFileRes) => {
        let data = JSON.parse(uploadFileRes.data);
        console.log(data, "data");

        if (data.code == 200) {
          console.log(
            "data.data.url________",
            payobj.value.operating_area.street_code
          );
          try {
            let ress = await newAgencyCreate({
              ...payobj.value,
              signature: data.data.url,
              code: payobj.value.operating_area.street_code,
            });

            if (ress.code == 200) {
              dateobj.formdate.signature = data.data.url;
              uni.navigateTo({
                url:
                  "/pages/upgrade/upgradepay?id=" +
                  (ress.data.id ? ress.data.id : "") +
                  "&payobj=" +
                  JSON.stringify(payobj.value),
              });
              dateobj.setformdate({});
              // paid.value = ress.data.id;
              // upgradeshow.value = true;

              // level_id.value = e.level_id ? e.level_id : "";
              // id.value = e.id ? e.id : "";
              // product_id.value = e.product_id ? e.product_id : "";
              // if (pay_status.value) {

              //   uni.reLaunch({
              //     url: "/pages/upgrade/upgradestate?type=1",
              //   });
              // } else {
              //   uni.reLaunch({
              //     url: "/pages/upgrade/upgradestate?type=1",
              //   });
            }
          } catch (e) {
            uni.hideLoading();
            istj.value = false;
            uni.$u.toast(e + "请返回重新选择");

            if (pay_status.value) {
              dateobj.setformdate({});
              uni.reLaunch({
                url: "/pages/upgrade/upgradestate?type=2",
              });
            }
          }
        }
      },
      fail: function (e) {
        console.log(e);
        istj.value = false;
        uni.hideLoading();
      },
    });
  } catch (error) {
    console.error("生成图片失败", error);
    uni.hideLoading();
    istj.value = false;
    uni.$u.toast("生成图片失败");
  }

  return;
};

const finushfun = () => {
  isCountDown.value = true;
};

const generateImage = async () => {
  nextTick(() => {
    // console.log(capture.value);

    console.log(capture.value.textContent, aaa2.value.text);
  });
  try {
    const element = capture.value;
    console.log(element);
    const canvas = await html2canvas(element, {
      useCORS: true, // 允许跨域图片
      allowTaint: false, // 不允许污染
    });
    const dataURL = canvas.toDataURL("image/png");
    console.log(dataURL); // 这里可以将 dataURL 保存或显示
  } catch (error) {
    console.error("生成图片失败", error);
  }
};

// position: absolute;top: 0; left: 0;opacity:0;
function wxnurl() {
  let paramsurl =
    "/pages/upgrade/upgradepay?id=" +
    (ress.data.id ? ress.data.id : "") +
    "&payobj=" +
    JSON.stringify(dateobj.formdate);
  return `<wx-open-launch-weapp  class="launch-weapp" id="launch-btn" appid="wxbbb8ed3d5b5ada72" username="gh_d08f4ffdf5cc"  path="${paramsurl}" style=" z-index: 99;display: block;width: 100%;height: 100%;opacity:0;overflow: hidden;" > \<script  type="text/wxtag-template" style="display: block; height: 170px; width: 100%; z-index: 99;"\>\<button style="height: 170px; width: 100%; z-index: 99; display: block"\>点击跳转小程序\<\/button\>\<\/script\></wx-open-launch-weapp>`;
}
function wxnurl2() {
  let paramsurl =
    "/pages/upgrade/upgradepay?id=" +
    paid.value +
    "&payobj=" +
    JSON.stringify(payobj.value);
  return `<wx-open-launch-weapp  class="launch-weapp" id="launch-btn" appid="wx68f8fad3e517f048" username="gh_c65daa57f8f9"  path="${paramsurl}" style=" z-index: 9999;position: absolute;top: 0; left: 0;display: block;width: 100%;height: 100%;opacity:0;overflow: hidden;" > \<script  type="text/wxtag-template" style="display: block; height: 170px; width: 100%; z-index: 99999;opacity:0;"\>\<button style="height: 170px; width: 100%; z-index: 99; display: block"\>点击跳转小程序\<\/button\>\<\/script\></wx-open-launch-weapp>`;
}
</script>

<template>
  <view class="upgrade">
    <stepsview :current="current"></stepsview>

    <view class="agreement-content">
      <view class="agreement-title"></view>

      <div ref="capture">
        <view class="agreement-text"
          ><up-parse :content="contentobj"></up-parse>
        </view>
        <image class="signature-img" :src="signature" mode="scaleToFill" />
      </div>

      <view class="signature-k">
        <xz-signature ref="signqm" @clear="clearshart" @save="signatureEvent" />
      </view>
    </view>
  </view>

  <view class="foodr-bt">
    <!-- <view class="bt-next" @click="lastfun">上一步</view> -->
    <view
      class="bt-sbuit"
      @click="nextfun"
      :class="!isCountDown ? 'bt-sbuit-none' : ''"
      ><u-count-down
        :time="3 * 1000"
        format="ss"
        @finish="finushfun"
        @change="onChange"
        ><text v-if="!isCountDown">{{ time + 1 }}秒后</text>
        同意协议</u-count-down
      >
    </view>
  </view>

  <up-popup
    :show="upgradeshow"
    mode="center"
    round="10"
    @close="close"
    @open="open"
  >
    <view class="popup-content">
      <view class="popup-content-title">签署</view>
      <view class="popup-content-dec">您已签署协议， 前往付款完成</view>
      <view class="popup-content-bt">
        <!-- <view class="popup-content-qx" @click="upgradeshow = false">取消</view> -->
        <!-- <view v-html="wxnurl()"></view> -->
        <view class="popup-content-cl" @click="goupgrade">
          <text>去付款</text>
          <div v-html="wxnurl2()"></div>

          <!-- <wx-open-launch-weapp
            id="launch-btn"
            class="launch-weapp"
            appid="wxbbb8ed3d5b5ada72"
            username="gh_d08f4ffdf5cc"
            path="shopurl"
            style="z-index: 99; position: absolute; top: 0; left: 0"
          >
            <view
              v-is="'script'"
              type="text/wxtag-template"
              style="display: block; height: 170px; width: 100%; z-index: 99"
            >
              <button style="height: 170px; width: 100%; z-index: 99">
                点击跳转小程序
              </button>
            </view>
          </wx-open-launch-weapp> -->
        </view>
      </view>
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "./agreement.scss";

.popup-content {
  width: 616rpx;
  padding: 48rpx 48rpx;
  box-sizing: border-box;
  // height: 428rpx;
  background: #ffffff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  .popup-content-title {
    font-weight: bold;
    font-size: 32rpx;
    color: #262626;
    line-height: 52rpx;
    text-align: center;
  }
  .popup-content-dec {
    margin-top: 48rpx;
    font-weight: 400;
    font-size: 28rpx;
    color: #595959;
    line-height: 52rpx;
    text-align: center;
  }
  .popup-content-bt {
    margin-top: 48rpx;
    display: flex;
    // justify-content: space-between;
    justify-content: space-around;
    align-items: center;
  }
  .popup-content-qx {
    width: 246rpx;
    height: 80rpx;
    background: #eeeeee;
    border-radius: 982rpx 982rpx 982rpx 982rpx;
    font-weight: bold;
    font-size: 28rpx;
    color: #262626;
    line-height: 80rpx;
    text-align: center;
  }
  .popup-content-cl {
    width: 246rpx;
    height: 80rpx;
    background: #01ada8;
    border-radius: 982rpx 982rpx 982rpx 982rpx;
    font-weight: bold;
    font-size: 28rpx;
    color: #ffffff;
    line-height: 80rpx;
    text-align: center;
    position: relative;
  }
}

.launch-weapp {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
}
</style>
